<?php
/**
 * Product:     One-Page Checkout Booster
 * Package:     Gold_Gonepage_1.1.1_94708
 * Purchase ID: 9CBm2i1g9YwZZ6QK4IjUneSwxlnJsImwioL1MUWAXd
 * Generated:   2011-07-15 10:07:59
 * File path:   app/code/local/Gold/Gonepage/controllers/CheckoutController.php
 * Copyright:   (c) 2011 GOLD, Inc.
 */
class Gold_Gonepage_CheckoutController extends Gold_Gonepage_Controller_Action
{
    protected $_sectionSaveFunctions = array(
        'billing'           => 'saveBilling',
        'shipping'          => 'saveShipping',
        'shipping_method'   => 'saveShippingMethod',
        'payment'           => 'savePayment',
        'deliverydate'      => 'saveShippingMethod',
        'customreview'      => 'saveCustomReview',
    );
    
//    protected $_addressLoadFunctions = array(
//        'billing'           => 'getBillingAddress',
//        'shipping'          => 'getShippingAddress',
//    );
    
    protected function _ajaxRedirectResponse()
    {
        $this->getResponse()
            ->setHeader('HTTP/1.1', '403 Session Expired')
            ->setHeader('Login-Required', 'true')
            ->sendResponse();
        return $this;
    }
    
    protected function _expireAjax()
    {
        if (!$this->_getOnepage()->getQuote()->hasItems() 
            || $this->_getOnepage()->getCheckout()->getCartWasUpdated(true)) 
        {
            $this->_ajaxRedirectResponse();
            return true;
        }

        return false;
    }
    
    public function indexAction()
    {
        /* */
        $iStoreId = Mage::app()->getStore()->getId();
        $iSiteId  = Mage::app()->getWebsite()->getId();
        /*$performer = Gold_Goldsys_Abstract_Service::get()->platform()->getModule('Gold_Gonepage')->getLicense()->getPerformer();
        $ruler     = $performer->getRuler();
        if (!($ruler->checkRule('store', $iStoreId, 'store') || $ruler->checkRule('store', $iSiteId, 'website')))
        {
            $this->_redirect('checkout/onepage');
            return;
        }
         */
        
        if(Mage::helper('gonepage')->isDisabled())
        {
            $this->_redirect('checkout/onepage');
            return;
        }
    
        $quote = $this->_getOnepage()->getQuote();
        if (!$quote->hasItems() || $quote->getHasError()) {
            if (Mage::helper('gonepage')->isShowCheckoutOutsideCart())
            {
                $this->_redirect('checkout/cart');
                return;
            }
        }
        
        if ($quote->hasItems() && !$quote->validateMinimumAmount()) {
            $error = Mage::getStoreConfig('sales/minimum_order/error_message');
            $this->_getOnepage()->getCheckout()->addError($error);
            if (Mage::helper('gonepage')->isShowCheckoutOutsideCart())
            {
                $this->_redirect('checkout/cart');
                return;                
            }
        }

        foreach ($quote->getMessages() as $message) {
            if ($message) {
                $this->_getOnepage()->getCheckout()->addMessage($message);
            }
        }
        
        $this->_getOnepage()->getCheckout()->setCartWasUpdated(false);  
        Mage::getSingleton('customer/session')->setBeforeAuthUrl(Mage::getUrl('*/*/*', array('_secure'=>true)));
        $this->_getOnepage()->initCheckout();
        $this->loadLayout()
            ->_initLayoutMessages('checkout/session')
            ->_initLayoutMessages('catalog/session')
            ->getLayout()->getBlock('head')->setTitle(Mage::helper('gonepage')->getCheckoutTitle())
            ;
            
        if (Mage::helper('gonepage')->isShowCheckoutTitle())
        {
            $this->getLayout()
                ->getBlock('head')
                ->setTitle(
                    Mage::helper('gonepage')->__(Mage::helper('gonepage')->getCheckoutTitle()) 
                );
        } 
        else {
            $this->getLayout()
                ->getBlock('head')
                ->setTitle(
                    Mage::helper('gonepage')->__('Checkout')
                );
        }
        $this->renderLayout();       
    }  
    
    public function updateStepsAction()
    {
        if ($this->_expireAjax()) {
            return;
        }
        if ($this->getRequest()->isPost()) 
        {
            $data = $this->getRequest()->getPost();
            $currentStep = $data['step'];
            $data = $this->getRequest()->getPost($currentStep, array());
            $customerAddressId = null;
            switch($currentStep)
            { 
                case 'billing':
                case 'shipping':
                    Mage::getSingleton('checkout/session')->setConfirmSameAsBilling(1);
                    $customerAddressId = $this->getRequest()->getPost($currentStep . '_address_id', false);
                    break; 
                case 'shipping_method': 
                    break;
                case 'payment':
                    // save and unset cfm params 
//                    Mage::helper('gonepage/gonepagefields')->saveCustomData($data);    
//                    foreach ($data as $key => $val)
//                    {
//                        if (strpos($key, 'itoc_checkout_'))
//                        {
//                            unset($data[$key]);
//                        }
//                    }
                    break;
                case 'deliverydate':
                    $data = $this->getRequest()->getPost('shipping_method', array());
                    break;    
                case 'Ggiftwrap':
                case 'giftmessage':
                    Mage::dispatchEvent('checkout_controller_onepage_save_shipping_method', array('request'=>$this->getRequest(), 'quote'=>$this->_getOnepage()->getQuote()));
                    break;
            }
            
            $saveFunction = isset($this->_sectionSaveFunctions[$currentStep]) ? $this->_sectionSaveFunctions[$currentStep] : null;  
            $result = $saveFunction ? $this->_getOnepage()->$saveFunction($data, $customerAddressId) : null;

            $this->getResponse()
                ->setBody(
                    Mage::helper('core')->jsonEncode($this->_extractStepOutput($currentStep, $result))
                );
        }   
    }

//    public function getAddressAction()
//    {
//        if ($this->_expireAjax()) {
//            return;
//        }
//        
//        $addressId = $this->getRequest()->getParam('address', false);
//        
//        if ($addressId) {
//            $address = $this->_getOnepage()->getAddress($addressId);
//        } else {
//            $quote = $this->_getOnepage()->getQuote();
//            $addressType = $this->getRequest()->getParam('addressType', 'billing');
//            $getAddressFunction = $this->_addressLoadFunctions[$addressType];
//            $address = $quote->$getAddressFunction();
//            $address->explodeStreetAddress();
//        }
//        
//        if (Mage::getSingleton('customer/session')->getCustomer()->getId() == $address->getCustomerId()) {
//            $this->getResponse()->setHeader('Content-type', 'application/x-json');
//            $this->getResponse()->setBody($address->toJson());
//        } else {
//            $this->getResponse()->setHeader('HTTP/1.1','403 Forbidden');
//        }
//    } 

}